package com.google.code.jwebannotation;

import java.lang.reflect.Method;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class BeanFunctions {

	private static Log log = LogFactory.getLog(BeanFunctions.class);

	public static Object populate(Class<?> clazz, HttpServletRequest request)
			throws InstantiationException, IllegalAccessException {
		Object obj = clazz.newInstance();
		Enumeration<?> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			set(name, request.getParameter(name), obj);
		}
		return obj;
	}

	private static void set(String name, String value, Object obj) {
		log.debug("Setting '" + name + "' in object '" + obj.getClass() + "'");
		Method[] methods = obj.getClass().getMethods();
		for (Method m : methods) {
			String methodName = getName(m);
			if (methodName != null && methodName.equalsIgnoreCase(name)) {
				if (m.getParameterTypes().length == 1
						&& m.getParameterTypes()[0].equals(String.class)) {
					try {
						log.debug("Found method to use '" + m + "'");
						m.invoke(obj, value);
						return;
					} catch (Exception e) {
						log.error("An exception was caught trying to set parameter", e);
					}
				}
			}
		}
		log.debug("Parameter '" + name
				+ "' was not set in object because not suitable method was found");
	}

	private static String getName(Method m) {
		String name = m.getName();
		if (name.startsWith("set")) {
			return name.substring(3);
		}
		return null;
	}
}
